package cn.school.student.service.impl;

import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.student.dao.TExamTestpaperDao;

import cn.school.student.entity.ExamPublish;
import cn.school.student.entity.TExamCorrelation;
import cn.school.student.entity.TExamSubject;
import cn.school.student.entity.TExamTestpaper;
import cn.school.student.service.ExamPublishService;
import cn.school.student.service.TExamCorrelationService;
import cn.school.student.service.TExamSubjectService;
import cn.school.student.service.TExamTestpaperService;
import cn.school.student.vo.ChangeFolderVO;
import cn.school.sys.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 考試試卷表(TExamTestpaper)表服务实现类
 *
 * @author makejava
 * @since 2023-02-16 17:34:26
 */
@Service("tExamTestpaperService")
public class TExamTestpaperServiceImpl extends ServiceImpl<TExamTestpaperDao, TExamTestpaper> implements TExamTestpaperService {
    @Resource
    private TExamTestpaperDao tExamTestpaperDao;

    @Autowired
    private TExamSubjectService tExamSubjectService;

    @Autowired
    private TExamCorrelationService tExamCorrelationService;

    @Autowired
    private ExamPublishService examPublishService;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TExamTestpaper queryById(Long id) {
        return this.tExamTestpaperDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param tExamTestpaper 筛选条件
     * @param pageRequest    分页对象
     * @return 查询结果
     */
    @Override
    public IPage<TExamTestpaper> queryByPage(TExamTestpaper tExamTestpaper, PageRequest pageRequest) {
        tExamTestpaper.setCreateBy(SysUserUtils.getSysUser().getUsername());
        Integer count = (int) tExamTestpaperDao.count(tExamTestpaper);

        List<TExamTestpaper> examInfoList = tExamTestpaperDao.queryAllByLimit(tExamTestpaper, pageRequest);

        IPage<TExamTestpaper> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        page.setTotal(count);
        page.setRecords(examInfoList);
        return page;
    }

    /**
     * 新增数据
     *
     * @param tExamTestpaper 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insert(TExamTestpaper tExamTestpaper) {
        SysUser sysUser = SysUserUtils.getSysUser();

        tExamTestpaper.setCreateBy(sysUser.getUsername());

        tExamTestpaper.setCreateTime(new Date());
        tExamTestpaper.setType("1");
        Integer insert = tExamTestpaperDao.insert(tExamTestpaper);
        Long testpaperId = tExamTestpaper.getId();
        //用来存没有试题id的数据
        List<TExamSubject> subList = new ArrayList<>();
        //用来保存有试题ID的数据
        List<TExamCorrelation> corrList = new ArrayList<>();
        TExamCorrelation corr = null;
        for (TExamSubject tExamSubject : tExamTestpaper.getExamSubjectList()) {
            corr = new TExamCorrelation();
            if(StringUtils.isEmpty(tExamSubject.getId())){

                //添加试题，返回id后保存至试卷-试题关系表
                tExamSubjectService.insert(tExamSubject);
                corr.setScoresScore(tExamSubject.getScoresScore());
                corr.setQuestionsId(Long.valueOf(tExamSubject.getId()));
                corrList.add(corr);
            }else{

                corr.setScoresScore(tExamSubject.getScoresScore());
                corr.setQuestionsId(Long.valueOf(tExamSubject.getId()));
                corrList.add(corr);
            }
        }

        for (TExamCorrelation correlation : corrList) {
            correlation.setTestpaperId(testpaperId);
        }

        Integer integer = tExamCorrelationService.insertBatch(corrList);


        return insert;

    }

    /**
     * 修改数据
     *
     * @param tExamTestpaper 实例对象
     * @return 实例对象
     */
    @Override
    public Integer update(TExamTestpaper tExamTestpaper) {
        QueryWrapper<ExamPublish> examPublishQueryWrapper = new QueryWrapper<>();
        examPublishQueryWrapper.eq("test_paper_id", tExamTestpaper.getId());
        int count = this.examPublishService.count(examPublishQueryWrapper);
        if (count > 0) {
            throw new ApiException("已发布的试卷不能更新！");
        }


        SysUser sysUser = SysUserUtils.getSysUser();
        QueryWrapper<TExamCorrelation> wrapper = new QueryWrapper();
        tExamTestpaper.setModifyBy(sysUser.getUsername());
        tExamTestpaper.setModifyTime(new Date());
        Integer update = this.tExamTestpaperDao.updateById(tExamTestpaper);
        this.tExamCorrelationService.remove(wrapper.eq("testpaper_id", tExamTestpaper.getId()));


        //用来存没有试题id的数据
        List<TExamSubject> subList = new ArrayList<>();
        //用来保存有试题ID的数据
        List<TExamCorrelation> corrList = new ArrayList<>();
        TExamCorrelation corr = null;
        for (TExamSubject tExamSubject : tExamTestpaper.getExamSubjectList()) {
            corr = new TExamCorrelation();
            if(StringUtils.isEmpty(tExamSubject.getId())){
                //添加试题，返回id后保存至试卷-试题关系表
                tExamSubject.setCreateTime(new Date());
                tExamSubject.setCreateBy(SysUserUtils.getSysUser().getUsername());
                tExamSubjectService.insert(tExamSubject);
                corr.setScoresScore(tExamSubject.getScoresScore());
                corr.setQuestionsId(Long.valueOf(tExamSubject.getId()));
                corrList.add(corr);
            }else{
                corr.setScoresScore(tExamSubject.getScoresScore());
                corr.setQuestionsId(Long.valueOf(tExamSubject.getId()));
                corrList.add(corr);
            }
        }

        for (TExamCorrelation correlation : corrList) {
            correlation.setTestpaperId(tExamTestpaper.getId());
        }

        this.tExamCorrelationService.insertBatch(corrList);
        return update;

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        QueryWrapper<ExamPublish> examPublishQueryWrapper = new QueryWrapper<>();

        QueryWrapper<TExamCorrelation> examCorrelationQueryWrapper = new QueryWrapper<>();

        examPublishQueryWrapper.eq("test_paper_id", id);
//        examPublishQueryWrapper.eq("status", "1");

        int count = this.examPublishService.count(examPublishQueryWrapper);

        if (count > 0) {

            throw new ApiException("已发布的试卷不能删除！");
        }
        tExamCorrelationService.remove(examCorrelationQueryWrapper.eq("testpaper_id", id));

        return this.tExamTestpaperDao.deleteById(id) > 0;
    }

    @Override
    public TExamTestpaper examinationDetails(Long studentId, String result) {
        TExamTestpaper tExamTestpaper = this.tExamTestpaperDao.queryById(studentId);
        List<TExamSubject> tExamTestpaperVos = this.tExamCorrelationService.queryQuestionsIdList(studentId);


        tExamTestpaper.setExamSubjectList(tExamTestpaperVos.stream().filter(TExamSubject -> TExamSubject!=null).collect(Collectors.toList()));


        return tExamTestpaper;
    }

    @Override
    public Integer editFolder(TExamTestpaper tExamTestpaper) {
        tExamTestpaper.setType("0");
        Integer num=0;
        if(StringUtils.isEmpty(tExamTestpaper.getId())){
            tExamTestpaper.setCreateBy(SysUserUtils.getSysUser().getUsername());
            tExamTestpaper.setCreateTime(new Date());
            num = this.tExamTestpaperDao.insert(tExamTestpaper);
        }else{
            tExamTestpaper.setModifyBy(SysUserUtils.getSysUser().getUsername());
            tExamTestpaper.setModifyTime(new Date());
            num = this.tExamTestpaperDao.updateById(tExamTestpaper);
        }
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteFolder(List<String> ids) {
        Integer num=0;
        for (String id : ids) {
            //删除文件夹
            this.tExamTestpaperDao.deleteById(Long.valueOf(id));
            LambdaQueryWrapper<TExamTestpaper> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TExamTestpaper::getPid,id);
            //删除文件夹中的试卷
            this.tExamTestpaperDao.delete(wrapper);
            num ++;
        }
        return num;
    }

    @Override
    public Integer changeToFolder(ChangeFolderVO vo) {
        Integer num=0;
        List<TExamTestpaper> testPaperList = vo.getTestPaperList();
        for (TExamTestpaper tExamTestpaper : testPaperList) {
            tExamTestpaper.setPid(String.valueOf(vo.getPid()));
            num=this.tExamTestpaperDao.updateById(tExamTestpaper);
        }

        return num;
    }

    @Override
    public List<TExamTestpaper> findMysafeAllFolder() {
        LambdaQueryWrapper<TExamTestpaper> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TExamTestpaper::getType,"0");
        wrapper.eq(TExamTestpaper::getTenantId, SysUserUtils.getSysUser().getTenantId());
        wrapper.eq(TExamTestpaper::getCreateBy,SysUserUtils.getSysUser().getUsername());
        wrapper.orderByAsc(TExamTestpaper::getType).orderByDesc(TExamTestpaper::getCreateTime);

        List<TExamTestpaper> list = tExamTestpaperDao.selectList(wrapper);
        return list;
    }
}
